<?php
error_reporting(1);
ini_set('display_errors', 'on');
Workerman\Protocols\Http::sessionStart();
if(!isset($_SESSION['USER_ID']) ||!isset($_SESSION['ACCESS_TOKEN'])){
    Workerman\Protocols\Http::header("Location: ./login.php");
    Workerman\Protocols\Http::end();
}
$id = $_GET["id"];
$title = $_GET["title"];
$history = @$_GET["history"];
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>莲花在线校稿系统</title>
    <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <link rel="stylesheet" href="./css/sm.css">
    <link rel="stylesheet" href="./css/sm-extend.css">
    <link rel="stylesheet" href="./css/drag.css">
    <style>
        body { touch-action: none; }
    </style>
</head>
<body>




<div class="page-group">
    <!-- 你的html代码 -->
    <div class="page page-current" id="page-1581651169664">
        <header class="bar bar-nav" id="header">
            <?php if($history == 1){ ?>

                <a class="button button-link button-nav pull-left" href="./history.php">
                    <span class="icon iconfont-sm">&#xe744;</span>
                    返回
                </a>

            <?php }else{ ?>

                <a class="button button-link button-nav pull-left" href="./index.php">
                    <span class="icon iconfont-sm">&#xe744;</span>
                    返回
                </a>
                <button class="button pull-right" id="save">
                    保存
                </button>

            <?php } ?>

            <h1 id="contents_title" class="title"><?php echo $title;?><span id="page_number"></span></h1>
        </header>
        <nav class="bar bar-tab" id="nav">
            <?php if(empty($history)){ ?>
                <a class="tab-item external prompt-add-text" href="#">
                    <span class="icon iconfont-sm">&#xe768;</span>
                    <span class="tab-label">添加标注</span>
                </a>
            <?php }?>

            <a class="tab-item external add-btn-update" href="#" style="display: none;">
                <span class="icon icon-check-sm">✔</span>
                <span class="tab-label">全部确认</span>
            </a>

            <a class="tab-item external prompt-list-text select-btn-list" href="#">
                <span class="icon iconfont-sm">&#xe6fd;</span>
                <span class="tab-label">标注列表</span>
                <span class="badge" id="list-text-badge">0</span>
            </a>
            <!--
            <a class="tab-item external prompt-source-img" href="#">
              <span class="icon iconfont-sm">&#xe6fd;</span>
              <span class="tab-label">显示原图</span>
            </a-->
        </nav>
        <div id="content" class="content native-scroll">
            <div id="page_area_div" style="display: flex;justify-content: center;align-items: center;padding: 5px 0;background: #f4f4f4;">
                <label for="" style="font-size:15px;">选择页数：</label> <input type="text" style="text-align:center;height: 20px;font-size: 12px;" id='picker-page'/>
                <button class="rejection" style="height: 20px;font-size: 12px;line-height: 20px;margin: 0 20px;color: red;border: none;display: none;">退稿</button>
            </div>
            <canvas id='myCanvas_oo' width="100%" height="100%"></canvas>
            <!-- 这里是页面内容区
            <img src="" alt="Picture 2"/>-->
            <!--
              <iframe id="iframe_content" src="./home/index.html?id=<?php echo $id;?>" height="100%" width="100%"></iframe>
              -->
        </div>
         About Popup
                  <div class="popup popup-about">
                    <header class="bar bar-nav">
                      <a class="button button-link button-nav pull-left close-popup" href="#">
                        关闭
                      </a>
                      <h1 class="title">标注列表</h1>
                    </header>
                    <div class="content" style="background-color: #efeff4;">
                        <div id="popup-content"></div>
                        <div class="content-block">

                        </div>
                    </div>
                  </div>






    </div>
</div>
<script type="text/javascript" src="./js/zepto.min.js" charset="utf-8"></script>
<script type="text/javascript" src="./js/sm.js" charset="utf-8"></script>
<script type="text/javascript" src="./js/sm-extend.js" charset="utf-8"></script>
<script src="./js/drag.js"></script>

<script src="./js/hammer.min.js"></script>

<script src="./js/fabric400.js" type="text/javascript"></script>
<script type="text/javascript" src="./js/common.js" charset="utf-8"></script>
<!--<script src="js/fabric_with_gestures.js" type="text/javascript"></script>-->
<script> //传入容器ID就可以

    $(function(){
        var textObj = "";
        var identity = localStorage.getItem("identity");

        console.log("<?php echo $history;?>" , "1111");

        $('.select-btn-list')[0].style.display = "table-cell";


        if((identity == 3 || identity == 2) && "<?php echo $history;?>"  != 1){
            $(".rejection")[0].style.display = "block";
        }

        if(identity == 3 || identity == 2){
            $('.add-btn-update')[0].style.display = "table-cell";
        }

        var deleteIcon = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg version='1.1' id='Ebene_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='595.275px' height='595.275px' viewBox='200 215 230 470' xml:space='preserve'%3E%3Ccircle style='fill:%23F44336;' cx='299.76' cy='439.067' r='218.516'/%3E%3Cg%3E%3Crect x='267.162' y='307.978' transform='matrix(0.7071 -0.7071 0.7071 0.7071 -222.6202 340.6915)' style='fill:white;' width='65.545' height='262.18'/%3E%3Crect x='266.988' y='308.153' transform='matrix(0.7071 0.7071 -0.7071 0.7071 398.3889 -83.3116)' style='fill:white;' width='65.544' height='262.179'/%3E%3C/g%3E%3C/svg%3E";
        var img = document.createElement('img');
        img.src = deleteIcon;

        //添加处理缓存
        fabric.textureSize = 4096;

        // 当前编辑的picture_department_id
        var CUREENT_PICTURE_DEPARTMENT_ID = -1;
        var CUREENT_PICTURE_DATA = [];
        var _poster_id = '<?php echo $G_MODEL_GET_POSTER_ID;?>';
        console.log(_poster_id , "111111111111111111111111111")
        var object_selected = false;
        var canvas = new fabric.Canvas('myCanvas_oo');

        canvas.preserveObjectStacking = true;   //不允许选择object后改变层位置
        canvas.selection = false;               //不允许画布选择

        // ========================= 自定义控件 ===========================

        // // 自定义object按键，添加删除按键
        // fabric.Object.prototype.controls.deleteControl = new fabric.Control({
        //     position: { x: 0.5, y: -0.5 },
        //     offsetY: 10,
        //     cursorStyle: 'pointer',
        //     mouseUpHandler: deleteObject,
        //     render: renderIcon,
        //     cornerSize: 24
        // });
        //
        // // 处理对象删除事件
        // function deleteObject(eventData, target) {
        //     var canvas = target.canvas;
        //     target.off("mousedown");
        //     target.off("mouseup");
        //     canvas.remove(target);
        //     canvas.requestRenderAll();
        //     object_selected = false;
        //     text_count();
        // }
        //
        // function renderIcon(ctx, left, top, styleOverride, fabricObject) {
        //     if (!this.getVisibility(fabricObject)) {
        //         return;
        //     }
        //     var size = this.cornerSize;
        //     ctx.save();
        //     ctx.translate(left, top);
        //     ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
        //     ctx.drawImage(img, -size/2, -size/2, size/2, size/2);
        //     ctx.restore();
        // }

        // ================= 加载页面后，更新画布大小 =========================
        canvas.setWidth( $("#content").width());
        canvas.setHeight( $("#content").height()-$("#page_area_div").height()-2 );
        canvas.calcOffset();
        canvas.requestRenderAll();

        $("#content").on('resize',function(){
            setTimeout(function(){
                //$("#myCanvas_oo").attr("width", $("#upper-canvas").width());
                //$("#myCanvas_oo").attr("height", document.body.clientHeight-265);
                canvas.setWidth( $("#content").width());
                canvas.setHeight($("#content").height()-$("#page_area_div").height()-2 );
                canvas.calcOffset();
                canvas.requestRenderAll();
            },500);
        });

        // ======================= 处理画布移动和放大缩小事件 ==============================
        var myElement = document.getElementById('content');  //将content层作为手势获取层
        var mc = new Hammer(myElement);

        //初始化 pan 单手指事件和 pinch 双手放大缩小事件
        mc.get('pan').set({ direction: Hammer.DIRECTION_ALL });
        mc.get('pinch').set({ enable: true });
        // listen to events...
        var deltaX, deltaY;

        //canvas整体移动的事件
        mc.on("panstart  panmove panend", function(ev) {
            if(object_selected)  //如果有选择对象，则不进行方法缩小或者移动
                return;

            // 移动结束后的事件
            if(ev.type=="panend"){
                let filter = new fabric.Image.filters.Contrast({
                    contrast: -0.3
                });
                let os = canvas.getObjects();
                for(i in os){
                    if(os[i].type=="image"){
                        os[i].filters = [];
                        os[i].filters.push(filter);
                        os[i].applyFilters();
                        canvas.requestRenderAll();
                        break;
                    }
                }
            }

            // 移动开始前的事件
            if(ev.type=="panstart"){
                deltaX = ev.center.x;
                deltaY = ev.center.y;
                let os = canvas.getObjects();
                for(i in os){
                    if(os[i].type=="image"){
                        os[i].filters = [];
                        os[i].applyFilters();
                        canvas.requestRenderAll();
                        break;
                    }
                }
            }

            // 画布移动中
            if(ev.type=="panmove"){
                deltaX = ev.center.x - deltaX;
                deltaY = ev.center.y - deltaY;
                let delta = new fabric.Point(deltaX, deltaY);
                canvas.relativePan(delta);
                deltaX = ev.center.x;
                deltaY = ev.center.y;
            }
        });

        //放大缩小事件
        mc.on("pinchin pinchout", function(ev) {
            //console.log(ev);
            //console.log(ev.type +":" + ev.pointers.length + ":" + ev.distance +" gesture detected.");
            let distance = ev.distance;
            if(ev.type=="pinchin"){
                distance = distance;
            }
            if(ev.type=="pinchout"){
                distance = 0-distance;
            }

            let zoom = -0.0005*distance + canvas.getZoom();
            zoom = Math.max(0.1, zoom); //最小为原来的1/10
            zoom = Math.min(1.5, zoom); //最大是原来的3倍
            let zoomPoint = new fabric.Point(ev.center.x, ev.center.y);
            canvas.zoomToPoint(zoomPoint, zoom);
        });
        // ================== event end =======================================

        // ================== 获取画布中所有的文字标识 ========================
        function get_texts(){
            let os = canvas.getObjects();
            let rtval = [];
            let rtvalInfo = [];
            let rtvalIs_confirm = [];
            let rtvalTagging = [];
            let revalLocking = [];
            let revalDepartment_name = [];
            for(i in os){
                if(os[i].type=="i-text" || os[i].type=="text"){
                    rtval.push(os[i].toJSON());
                    rtvalInfo.push({info:os[i].info});
                    rtvalIs_confirm.push({is_confirm:os[i].is_confirm});
                    rtvalTagging.push({tagging:os[i].tagging});
                    revalLocking.push({locking:os[i].locking});
                    revalDepartment_name.push({department_name:os[i].department_name});
                }
            }
            for (let i = 0; i < rtval.length;i++){
                Object.assign(rtval[i] , rtvalInfo[i] , rtvalIs_confirm[i] , rtvalTagging[i] , revalLocking[i] ,revalDepartment_name[i]);
            }


            return rtval;
        }

        // ================== 将Json导入到canvas中 ============================
        function set_texts(json_data){
            for(let i in json_data){
                add_text(t=json_data[i].text, highlight=false, json=json_data[i] , lockingIndex=i)
            }
        }
        let dataInfo =  {
            "sku": "",
            "unit": "",
            "price": "",
            "name": "",
            "desc": "",
            "page": "",
            "idx": "",
            "s_price": "",
            "limit": "",
            "area_time": "",
            "mark": "",
            "origin": "",
            "flag": "",
            "department_name": ""
        };
        // ================== 添加标注的函数 ==================================
        // 当参数为json的时候，优先处理json
        function add_text(t=' 标注 ', highlight=false, json=null , lockingIndex){
            let addTextBool = false;
            if (!json){
                get_texts().map(item=>{
                    if (item.text == ' 标注 ') {
                        $.alert("已存在一个'标注'标记，请修改。重新添加")
                        addTextBool = true;
                    }
                })
                if (addTextBool) return
            }
            

            let color = '#000';
            if(highlight)
                color = '#F00';
            let p = canvas.getCenter();
            let vp = canvas.getVpCenter();
            let left = vp.x-20;
            let top = vp.y-20;
            let info = dataInfo;
            let tagging = "";
            let is_confirm = false;
            let locking = [false , false , false , false];
            let department_name = "";

            if(json!=null){
                if(typeof(json['left'])!='undefined' && typeof(json['top'])!='undefined'){
                    left = json['left'];
                    top  = json['top'];
                }
                if(typeof(json['fill'])!='undefined'){
                    color = json['fill'];
                }
                if(typeof(json['text'])!='undefined'){
                    t = json['text'];
                }
                if (typeof(json['info']) != 'undefined'){
                    info = json['info'];
                }
                if (typeof(json['tagging']) != 'undefined'){
                    tagging = json['tagging'];
                }
                if (typeof(json['is_confirm']) != 'undefined'){
                    is_confirm = json['is_confirm'];
                }
                if (typeof(json['locking']) != 'undefined'){
                    locking = json['locking'];
                }
                if (JSON.stringify(info) == JSON.stringify(dataInfo)){
                    department_name = get_texts()[0].info.department_name;
                }else{
                    department_name = info.department_name;
                }
            }else{
                department_name = get_texts()[0].info.department_name;
            }


            let text = null;

            let selected = "";
            if (locking[identity]){
                text  =new fabric.Text(t,{
                    left:left,
                    top:top,
                    fill: "#2d8cf0",
                    fontFamily: 'Comic Sans',
                    backgroundColor: 'rgba(255,255,255,0.8)',
                    fontSize:35,
                    padding:10,
                    borderScaleFactor:3,
                    fontWeight: 'bold'
                });
                oselected = false;
            } else {
                text  =new fabric.IText(t,{
                    left:left,
                    top:top,
                    fill: "#F00",
                    fontFamily: 'Comic Sans',
                    backgroundColor: 'rgba(255,255,255,0.8)',
                    fontSize:35,
                    padding:10,
                    borderScaleFactor:3,
                    fontWeight: 'bold'
                });
                selected = true;
            }


            text.info = info;
            text.tagging = tagging;
            text.is_confirm = is_confirm;
            text.locking = locking;
            text.department_name = department_name;

            var i = 0;

            text.on('mousedown', function() {
                i++;
                setTimeout(function () {
                    i = 0;
                }, 500);

                if (i > 1) {
                    if(JSON.stringify(info) != JSON.stringify(dataInfo)){
                        text_list(this.info , this.text , this.locking[identity]);
                        $.popup('.popup-about');
                    }else {
                        text_list(this.tagging , this.text , this.locking[identity]);
                        $.popup('.popup-about');
                    }
                    i = 0;
                }else{
                    if(JSON.stringify(info) == JSON.stringify(dataInfo)){
                        object_selected = selected;
                    }
                }
            });

            text.on('mouseup', function() {
                object_selected = false;
            });

            text.on('editing:exited', function() {

                let textArr = get_texts().map(item=>{return item.text;} );
                let newTextArr = [];
                let newTextArr2 = [];
                textArr.map(item=>{
                    if (newTextArr.indexOf(item) === -1){
                        newTextArr.push(item)
                    }else {
                        newTextArr2.push(item)
                    }
                });

                if (newTextArr2.length > 0){
                    $.alert("标记文本有重复 ， 请修改···");
                    this.text = t;
                    return
                }

                //添加左右空格
                let s = this.text;
                s = s.replace(/(^\s*)|(\s*$)/g, "");
                s = " " + s + " ";
                this.text = s;
            });

            text.lockScalingX = true;
            text.lockScalingY = true;
            text.lockRotation = true;
            canvas.add(text);
            text_count();
        }

        // ### 采购员和副总监
        //var raw_data = [{"name":"第1页","sub":[{"name":"广佛版","id":"","picture_path":"","contents":""},{"name":"粤西版","id":"","picture_path":"","contents":""}]},{"name":"第2页","sub":[{"name":"粤东版","id":"","picture_path":"","contents":""},{"name":"钦州版","id":"","picture_path":"","contents":""}]}];

        // ### 总监
        //var raw_data = [{"name":"干货1部","sub":[{"name":"第1页","sub":[{"name":"广佛版","id":"","picture_path":"","contents":""},{"name":"粤西版","id":"","picture_path":"","contents":""}]},{"name":"第2页","sub":[{"name":"粤东版","id":"","picture_path":"","contents":""},{"name":"钦州版","id":"","picture_path":"","contents":""}]}]},{"name":"干货2部","sub":[{"name":"第1页","sub":[{"name":"广佛版","id":"","picture_path":"","contents":""},{"name":"粤西版","id":"","picture_path":"","contents":""}]},{"name":"第2页","sub":[{"name":"粤东版","id":"","picture_path":"","contents":""},{"name":"钦州版","id":"","picture_path":"","contents":""}]}]}];


        var data = {action:"get_poster_contents",param:{id:"<?php echo $id;?>",user_id:"<?php echo $_SESSION['USER_ID'];?>",history:"<?php echo $history;?>"}};
        var param = {url:"<?php echo $_SESSION["MOBILE_URL"];?>",type:"POST",dataType:"JSON",data:JSON.stringify(data),access_token:"<?php echo $_SESSION['ACCESS_TOKEN']?>"};
        var textObj_id = "";
        var textObj_path = "";
        var preservationData  = "";
        ajax_request(param,function(result){
            if(result["rtval"].length <= 0){
                alert("数据加载失败，请稍后再试");
                return;
            }

            preservationData = result.rtval

            var errcode = result["errcode"];
            // errcode为4005，代表是总监，0代表采购员或副总监
            if(errcode == "4005"){
                var rtval = result["rtval"];
                raw_data = rtval;
                // 部门
                var department = raw_data.map(function(d) {
                    return d.name;
                });

                var initPages = sub(raw_data[0]);
                var initAreas = sub(raw_data[0]["sub"][0]);

                var currentDepartment = department[0];
                var currentPage = initPages[0];
                var currentArea = initAreas[0];



                $("#picker-page").val(currentDepartment+" "+currentPage+" "+currentArea);
                var t;
                // 选择页数
                $("#picker-page").picker({
                    toolbarTemplate: '<header class="bar bar-nav">\
                        <button class="button button-link pull-right close-picker">确定</button>\
                        <h1 class="title">请选择页数</h1>\
                        </header>',
                    cols: [
                        {
                            textAlign: 'center',
                            values: department
                        },
                        {
                            textAlign: 'center',
                            values: initPages
                        },
                        {
                            textAlign: 'center',
                            values: initAreas
                        }
                    ],

                    onOpen:function(picker){



                        let open_page = picker.cols[1].value[1];
                        let open_department = picker.cols[0].value;
                        console.log(picker.cols[1].value)


                        console.log(preservationData)

                        let index = "";
                        preservationData.map((item , i)=>{
                            if(item.name == open_department){
                                index = i
                            }
                        })



                        let contents_bool = false;

                        for(let j = 0; j < JSON.parse(preservationData[index].sub[open_page-1].sub[0].contents).length; j++){
                            if(JSON.stringify(JSON.parse(preservationData[index].sub[open_page-1].sub[0].contents)[j].locking) != JSON.stringify(get_texts()[j].locking)){
                                contents_bool = true;
                            }
                        }

                        if (JSON.parse(preservationData[index].sub[open_page-1].sub[0].contents).length != get_texts().length || contents_bool){
                            onBtnPreservation()
                            // raw_data[open_page].sub[0].contents = JSON.stringify(get_texts())
                        }

                    } ,

                    onChange: function (picker, values, displayValues) {
                        var newDepartment = picker.cols[0].value;
                        var newPage;
                        if(newDepartment !== currentDepartment) {
                            // 如果Province变化，节流以提高reRender性能
                            clearTimeout(t);

                            t = setTimeout(function(){
                                var newPages = getPages(newDepartment);
                                newPage = newPages[0];

                                var newAreas = getAreas(newDepartment, newPage);
                                picker.cols[1].replaceValues(newPages);
                                picker.cols[2].replaceValues(newAreas);
                                currentDepartment = newDepartment;
                                currentPage = newPage;
                                picker.updateValue();
                            }, 200);
                            return;
                        }
                        newArea = picker.cols[1].value;
                        if(newArea !== currentArea) {
                            currentArea = newArea;
                            picker.updateValue();
                        }
                    },
                    onClose:function(picker){
                        // 关闭钩子，获取当前部门、页、版本
                        var close_department = picker.cols[0].value;
                        var close_page = picker.cols[1].value;
                        var close_area = picker.cols[2].value;
                        for(var k in raw_data){
                            if(raw_data[k]["name"] == close_department){
                                var sub_arr = raw_data[k]["sub"];
                                for(var i in sub_arr){
                                    console.log()
                                    if(sub_arr[i]["name"] == close_page){
                                        var sub_page_arr = sub_arr[i]["sub"];
                                        for(var n in sub_page_arr){
                                            if(sub_page_arr[n]["name"] == close_area){
                                                textObj_id = sub_arr[i].sub[0].id;
                                                textObj_path = sub_arr[i].sub[0].picture_path;
                                                console.log(close_page , "11111");
                                                change_picture_path(sub_page_arr[n]["id"],sub_page_arr[n]["picture_path"],JSON.parse(sub_page_arr[n]["contents"]) , true);
                                            }

                                        }

                                    }
                                }
                            }
                        }

                    }

                });

                var first_id = raw_data[0]["sub"][0]["sub"][0]["id"];
                var first_picture_path = raw_data[0]["sub"][0]["sub"][0]["picture_path"];
                var first_contents = raw_data[0]["sub"][0]["sub"][0]["contents"];

                textObj_id = first_id;
                textObj_path = first_picture_path;
                change_picture_path(first_id,first_picture_path,JSON.parse(first_contents));
            }else{
                var rtval = result["rtval"];
                raw_data = rtval;
                var page = raw_data.map(function(d) {
                    return d.name;
                });
                var initAreas = sub(raw_data[0]);
                var currentPage = page[0];
                var currentArea = initAreas[0];
                $("#picker-page").val(currentPage+" "+currentArea);
                var t;
                // 选择页数
                $("#picker-page").picker({
                    toolbarTemplate: '<header class="bar bar-nav">\
                        <button class="button button-link pull-right close-picker">确定</button>\
                        <h1 class="title">请选择页数</h1>\
                        </header>',
                    cols: [
                        {
                            textAlign: 'center',
                            values: page
                        },
                        {
                            textAlign: 'center',
                            values: initAreas
                        }
                    ],
                    onOpen:function(picker){

                        let open_page = picker.cols[0].value[1];
                        let contents_bool = false;

                        for(let j = 0; j < JSON.parse(preservationData[open_page-1].sub[0].contents).length; j++){
                            if(JSON.stringify(JSON.parse(preservationData[open_page-1].sub[0].contents)[j].locking) != JSON.stringify(get_texts()[j].locking)){
                                contents_bool = true;
                            }
                        }

                        if (JSON.parse(preservationData[open_page-1].sub[0].contents).length != get_texts().length || contents_bool){
                            onBtnPreservation()
                            // raw_data[open_page].sub[0].contents = JSON.stringify(get_texts())
                        }

                    } ,
                    onChange: function (picker, values, displayValues) {
                        var newPage = picker.cols[0].value;
                        var newArea;
                        if(newPage !== currentPage) {
                            // 如果Province变化，节流以提高reRender性能
                            clearTimeout(t);

                            t = setTimeout(function(){
                                var newAreas = getPages(newPage);
                                newArea = newAreas[0];
                                picker.cols[1].replaceValues(newAreas);
                                currentPage = newPage;
                                currentArea = newArea;
                                picker.updateValue();
                            }, 200);
                            return;
                        }
                        newArea = picker.cols[1].value;
                        if(newArea !== currentArea) {
                            currentArea = newArea;
                            picker.updateValue();
                        }
                    },
                    onClose:function(picker){




                        // 关闭时间，获取当前页、版本
                        var close_page = picker.cols[0].value;
                        var close_area = picker.cols[1].value;
                        for(var k in raw_data){
                            if(raw_data[k]["name"] == close_page){
                                var sub_arr = raw_data[k]["sub"];
                                for(var i in sub_arr){
                                    if(sub_arr[i]["name"] == close_area){
                                        //切换页数
                                        textObj_id = sub_arr[i]["id"];
                                        textObj_path = sub_arr[i]["picture_path"];
                                        change_picture_path(sub_arr[i]["id"],sub_arr[i]["picture_path"],JSON.parse(sub_arr[i]["contents"]) , true);
                                    }
                                }
                            }
                        }

                    }
                });

                //CUREENT_PICTURE_DATA = rtval;

                var first_id = raw_data[0]["sub"][0]["id"];
                var first_poster_management_id = raw_data[0]["sub"][0]["poster_management_id"];
                var first_picture_path = raw_data[0]["sub"][0]["picture_path"];
                var first_contents = raw_data[0]["sub"][0]["contents"];
                textObj_id = first_id;
                textObj_path = first_picture_path;
                change_picture_path(first_id,first_picture_path,JSON.parse(first_contents));
            }
        })






        // 更换底图和切换picture_department_id
        var change_picture_path = function(picture_department_id, picture_path,contents , bool){
            // 获取当前身份
            var identity_data = {action:"get_user_data"};
            var identity_param = {url:"<?php echo $_SESSION["MOBILE_URL"];?>",type:"POST",dataType:"JSON",data:JSON.stringify(identity_data),access_token:"<?php echo $_SESSION['ACCESS_TOKEN']?>"};

            ajax_request(identity_param , function(result){
                identity =  result.rtval[0].class_level;
            })

            CUREENT_PICTURE_DEPARTMENT_ID = picture_department_id
            picture_path = "/poster_images"+picture_path;
            //console.log($("#iframe_content")[0].contentWindow)
            //$("#iframe_content")[0].contentWindow.initHistory("init_picture_department",picture_path);
            //console.log(picture_path);
            //==================================================
            // 载入图片
            $.showPreloader("海报图片加载中");
            canvas.clear();

            fabric.Image.fromURL(picture_path, function(oImg) {
                oImg.scale(1); //图片1倍显示
                oImg.lockRotation=true;
                canvas.add(oImg);
                oImg.set('selectable',false);


                if(!bool){
                    // 载入后给桌布缩小显示
                    let zoom = 0.5;
                    zoom = Math.max(0.2, zoom); //最小为原来的1/10
                    zoom = Math.min(1.5, zoom); //最大是原来的3倍
                    let delta = new fabric.Point(0-canvas.width/2, 0-canvas.height/2);
                    canvas.relativePan(delta);
                    let zoomPoint = new fabric.Point(canvas.width/2, canvas.height/2);
                    canvas.zoomToPoint(zoomPoint, zoom);
                }


                // 给图片灰度滤镜
                let filter = new fabric.Image.filters.Contrast({
                    contrast: -0.3
                });
                oImg.filters.push(filter);
                oImg.applyFilters();
                set_texts(contents);
                text_count();
                canvas.requestRenderAll();
                $.hidePreloader();



            });

            // 图片载入结束

        }

        // 默认页、默认版本
        // 结构
        // [{"name":"第1页","sub":[{"name":"广佛版","id":"","picture_path":"","contents":""},{"name":"粤西版","id":"","picture_path":"","contents":""}]},{"name":"第2页","sub":[{"name":"粤东版","id":"","picture_path":"","contents":""},{"name":"钦州版","id":"","picture_path":"","contents":""}]}]

        var format = function(data) {
            var result = [];
            for(var i=0;i<data.length;i++) {
                var d = data[i];
                if(d.name === "请选择") continue;
                result.push(d.name);
            }
            if(result.length) return result;
            return [""];
        };

        var sub = function(data) {
            if(!data.sub) return [""];
            return format(data.sub);
        };
        // 获取第二层
        var getPages = function(d) {
            for(var i=0;i< raw_data.length;i++) {
                if(raw_data[i].name === d) return sub(raw_data[i]);
            }
            return [""];
        };
        // 获取第三层
        var getAreas = function(p, c) {
            for(var i=0;i< raw_data.length;i++) {
                if(raw_data[i].name === p) {
                    for(var j=0;j< raw_data[i].sub.length;j++) {
                        if(raw_data[i].sub[j].name === c) {
                            return sub(raw_data[i].sub[j]);
                        }
                    }
                }
            }
            return [""];
        };

        // 添加标注
        $(document).on('click','.prompt-add-text', function () {
            let buttons1 = [
                {
                    text: '请选择',
                    label: true
                },
                {
                    text: '高亮标注',
                    bold: true,
                    color: 'danger',
                    onClick: function() {
                        if(get_texts().length <= 0){
                            $.alert("待设计师导入按钮校稿")
                        }else{
                            add_text(" 标注 ",true);
                            textObj = get_texts()
                        }


                    }
                },
                // {
                //     text: '普通标注',
                //     onClick: function() {
                //         // add_text(" 标注 ",false);
                //         //let o = get_texts();
                //         //set_texts(o);
                //     }
                // }
            ];
            let buttons2 = [
                {
                    text: '取消',
                    bg: 'danger'
                }
            ];
            let groups = [buttons1, buttons2];
            $.actions(groups);
        });


       $(document).on("click" , ".add-btn-update" , function () {
           let buttons1 = [
               {
                   text: '请选择',
                   label: true
               },
               {
                   text: '全部按钮确认',
                   bold: true,
                   color: 'danger',
                   onClick: function() {
                       textObj = get_texts();

                       for (let i = 0; i < textObj.length; i++){
                           textObj[i].locking[identity] = true;
                       }
                       change_picture_path(textObj_id , textObj_path , textObj , true);

                   }
               },

           ];
           let buttons2 = [
               {
                   text: '取消',
                   bg: 'danger'
               }
           ];
           let groups = [buttons1 ,buttons2];
           $.actions(groups);
       })

        // 标注列表
        $(document).on('click','.prompt-list-text', function () {
            text_list(false);
            $.popup('.popup-about');
        });

        // 保存 一个图片编辑完要保存一次
        $(document).on('click','#save', function () {
            let lockingBool = true;
            get_texts().map(item=>{
                if(!item.locking[identity]){
                    lockingBool = item.locking[identity]
                }
            });

            if (!lockingBool){
                $.alert("需要操作全部“确认修改”来表示，已完成工作");
                return
            }

            $.confirm('确定要保存？', function () {
                // 调用iframe中js的方法
                //var rt = $("#iframe_content")[0].contentWindow.override_save_method();
                var data = {action:"set_poster_contents",param:{picture_department_id:CUREENT_PICTURE_DEPARTMENT_ID,user_id:"<?php echo $_SESSION['USER_ID'];?>",contents:get_texts()}};
                var param = {url:"<?php echo $_SESSION["MOBILE_URL"];?>",type:"POST",dataType:"JSON",data:JSON.stringify(data),access_token:"<?php echo $_SESSION['ACCESS_TOKEN']?>"};


                let textArr = get_texts().map(item=>{return item.text;} );
                let newTextArr = [];
                let newTextArr2 = [];
                textArr.map(item=>{
                    if (newTextArr.indexOf(item) === -1){
                        newTextArr.push(item)
                    }else {
                        newTextArr2.push(item)
                    }
                });

                if (newTextArr2.length > 0){
                    $.alert("标记文本有重复 ， 请修改···")
                    return
                }

                ajax_request(param,function(result){
                    $.alert('保存成功');
                });
            });
        });

        function onBtnPreservation(sub_arr_id , sub_arr_path , sub_arr_contents , bool){
            //$.confirm('确定要保存？', function () {
            //    var data = {action:"set_poster_contents",param:{picture_department_id:CUREENT_PICTURE_DEPARTMENT_ID,user_id:"<?php //echo $_SESSION['USER_ID'];?>//",contents:get_texts()}};
            //    var param = {url:"<?php //echo $_SESSION["MOBILE_URL"];?>//",type:"POST",dataType:"JSON",data:JSON.stringify(data),access_token:"<?php //echo $_SESSION['ACCESS_TOKEN']?>//"};
            //    ajax_request(param,function(result){
            //        $.alert('保存成功');
            //        location.reload();
            //    });
            //});

            var r = confirm("你修改了內容 ， 是否保存？");
            if (r == true) {
                var data = {action:"set_poster_contents",param:{picture_department_id:CUREENT_PICTURE_DEPARTMENT_ID,user_id:"<?php echo $_SESSION['USER_ID'];?>",contents:get_texts()}};
                var param = {url:"<?php echo $_SESSION["MOBILE_URL"];?>",type:"POST",dataType:"JSON",data:JSON.stringify(data),access_token:"<?php echo $_SESSION['ACCESS_TOKEN']?>"};
                ajax_request(param,function(result){
                    $.alert('保存成功');
                    location.reload();
                });
            } else {
                x = "您按了取消！";
            }
        }



        //退稿
        $(document).on("click" , ".rejection" , function () {
            let out_data = {action:"back_poster_contents",param:{user_id:"<?php echo $_SESSION['USER_ID'];?>" , poster_picture_department_id:textObj_id}};
            let out_param = {url:"<?php echo $_SESSION["MOBILE_URL"];?>",type:"POST",dataType:"JSON",data:JSON.stringify(out_data),access_token:"<?php echo $_SESSION['ACCESS_TOKEN'];?>"};
            ajax_request(out_param,function(result) {
                $.alert(result.errmsg)
                setTimeout(_=>{window.location.href="javascript:history.go(-1)";} , 1000);

            })
        })

        // 统计标注数量
        function text_count(){
            $("#list-text-badge").text(get_texts().length);
        }

        // 属性保存
        var infoData = "";
        var tagginText = "";
        //修改内容按钮
        $(document).on("click" , ".tagging-btn" , function () {
            onUpdateInfo();
        })
        //确认修改按钮
        $(document).on("click" , ".locking-btn" , function () {
            onUpdateInfo(this);
        });

        //属性 “确定内容”和“确认修改”按钮操作
        function onUpdateInfo(el){
            let lockingId = "";
            textObj = get_texts();
            if(typeof infoData == "object"){
                let id = "";
                textObj.map((item , index)=>{
                    if(JSON.stringify(item.text) == JSON.stringify(tagginText)){
                        id = index
                        lockingId = index;
                    }
                })

                textObj.forEach((item , index)=>{
                    if(id == index){
                        item.info.sku = $(`#sku`).val(),
                            item.info.unit = $(`#unit`).val(),
                            item.info.price = $(`#price`).val(),
                            item.info.name= $(`#name`).val(),
                            item.info.desc = $(`#desc`).val(),
                            item.info.page = $(`#page`).val(),
                            item.info.idx = $(`#idx`).val(),
                            item.info.s_price = $(`#s_price`).val(),
                            item.info.limit = $(`#limit`).val(),
                            item.info.area_time = $(`#area_time`).val(),
                            item.info.mark = $(`#mark`).val(),
                            item.info.origin = $(`#origin`).val(),
                            item.info.flag = $(`#flag`).val(),
                            item.info.department_name = $(`#department_name`).val()
                    }
                })


                // for(key in textObj[id].info){
                //     if (!textObj[id].info[key]){
                //         $.alert("全部必填")
                //         return
                //     }
                // }


            }
            else if(typeof infoData == "string"){

                let tagging_id = "";
                textObj.map((item , index)=>{
                    if(JSON.stringify(item.text) == JSON.stringify(tagginText)){
                        tagging_id = index;
                        lockingId = index;
                    }
                })

                textObj.forEach((item , index)=>{
                    if(tagging_id == index){
                        item.tagging = $(`#tagging`).val();
                    }
                })


                if($(`#tagging`).val() == ""){
                    $.alert("必填标注说明")
                    return
                }

            }



            change_picture_path(textObj_id , textObj_path , textObj , true);

            if(el){
                textObj[lockingId].locking[identity] = !textObj[lockingId].locking[identity];
                if (textObj[lockingId].locking[identity]){
                    el.innerHTML = "取消修改"
                } else {
                    el.innerHTML = "确认修改";

                }
                $.alert("更改成功");
            }else{
                $.alert("保存成功");
            }

        }

        // 双击打开标注列表，展示所有标注
        function text_list(info , text , locking){
            infoData = info;
            tagginText = text;
            $("#popup-content")[0].innerHTML = "";
            if (typeof info == "object"){
                $("#popup-content")[0].innerHTML =  createElAttr(info ,text ,locking);
            }
            else if(typeof info == "string"){
                $("#popup-content")[0].innerHTML =  createElTagging(info , text , locking);
            }
            else if(typeof info == "boolean"){
                var index = 0;
                $("#popup-content").empty();

                for(let i in get_texts()){
                    index++;
                    if (JSON.stringify(get_texts()[i].info) == JSON.stringify(dataInfo)){
                        $("#popup-content").append('<div class="card" ><div class="card-content"><div class="card-content-inner">'+get_texts()[i].text+'</div></div></div>');
                    }else {
                        $("#popup-content").append('<div class="card" style="background: #cccccc;"><div class="card-content"><div class="card-content-inner">'+get_texts()[i].text+'</div></div></div>');
                    }
                }
            }




        }

        //创建按钮属性列表
        function createElAttr(info , T , locking){
            let lockingText = "确认修改";
            if(locking){
                lockingText = "取消修改";
            }
            let str = ""
            let text = {
                "sku": "sku",
                "unit": "unit",
                "price": "price",
                "name": "name",
                "desc": "desc",
                "page": "page",
                "idx": "idx",
                "s_price": "s_price",
                "limit": "limit",
                "area_time": "area_time",
                "mark": "mark",
                "origin": "origin",
                "flag": "flag",
                "department_name": "department_name"
            }
            for(key in info){

                let dis = "";

                if (key == "idx" || key == "department_name"){
                    dis = ` <textarea  disabled  id="${key}"   style="width: 70%;overflow-y:visible;">${info[key]}</textarea>`;
                } else{
                    dis = ` <textarea  id="${key}"   style="width: 70%;overflow-y:visible;">${info[key]}</textarea>`;
                }

                    str += `
                        <div class="card">
                        <div class="card-content">
                        <div class="card-content-inner" style="display: flex;">
                         <div style="width:20%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title="${text[key]}">${text[key]}</div>：
                           ${dis}
                        </div>
                        </div>
                       </div>
                    `;
            }

            str += `
                <div class="content-block">
                <div class="row" style="display: flex;justify-content: center;">
                  <div class="col-50"><a href="#" class="button button-big button-fill button-danger tagging-btn">修改内容</a></div>
                  <div class="col-50"><a href="#" class="button button-big button-fill button-danger locking-btn">${lockingText}</a></div>
                </div>
                </div>
                `;
            return str;
        }

        //创建标注输入框
        function createElTagging(taggingData , text ,locking){
            let lockingText = "确认修改";
            if(locking){
                lockingText = "取消修改";
            }
            return `
                <div class="card">
                <div class="card-content">
                <div class="card-content-inner">
                  <div style="margin-bottom: 10px;text-align: center;">${text}</div>
                   <textarea  style="width: 100%;height:300px;" id="tagging"  placeholder="请输入标注说明···">${taggingData}</textarea>
                </div>
                </div>
               </div>
             <div class="content-block">
                <div class="row" style="display: flex;justify-content: center;">
                  <div class="col-50"><a href="#" class="button button-big button-fill button-danger tagging-btn">修改内容</a></div>
                  <div class="col-50"><a href="#" class="button button-big button-fill button-danger locking-btn">${lockingText}</a></div>
                </div>
              </div>
                `;
        }


        var copy_texts = "";
        // 复制标注
        $(document).on('click','#btn_copy_texts', function () {
            console.log(get_texts());
            copy_texts = get_texts();
            $.toast("复制标注成功");

        });

        // 粘接标注
        $(document).on('click','#btn_bonding_texts', function () {
            if(copy_texts !=""){
                set_texts(copy_texts);
                $.toast("粘接标注成功");
            }
        });

        $.init();
    })


</script>
</body>
</html>